package com.vincce.sport.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.vincce.sport.core.utils.CheckUtil;
import com.vincce.sport.core.utils.Constant;
import com.vincce.sport.core.utils.ExcelUtil;
import com.vincce.sport.entity.CompetitionGroup;
import com.vincce.sport.entity.CompetitionTeam;
import com.vincce.sport.entity.School;
import com.vincce.sport.entity.Team;
import com.vincce.sport.mapper.CompetitionGroupMapper;
import com.vincce.sport.mapper.CompetitionTeamMapper;
import com.vincce.sport.mapper.SchoolMapper;
import com.vincce.sport.mapper.TeamMapper;

@Controller
@RequestMapping("/competitionTeam")
public class CompetitionTeamController extends BaseController{

	@Resource
	private CompetitionTeamMapper competitionTeamMapper;
	
	@Resource
	private CompetitionGroupMapper competitionGroupMapper;
	
	@Resource
	private TeamMapper teamMapper;
	
	@Resource
	private SchoolMapper schoolMapper;
	
	@RequestMapping("/list")
	public String list(Model model,Long seasonId){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("seasonId", seasonId);
		List<CompetitionGroup> competitionGroupList = competitionGroupMapper.findCompetitionGroupList(map);
		if(competitionGroupList == null || competitionGroupList.isEmpty()){
			String[] array = Constant.GROUP_ARRAY;
			for(String str : array){
				CompetitionGroup competitionGroup = new CompetitionGroup();
				competitionGroup.setSeasonId(seasonId);
				competitionGroup.setName(str);
				competitionGroupMapper.insert(competitionGroup);
				competitionGroupList.add(competitionGroup);
			}
		}else{
			for(CompetitionGroup competitionGroup : competitionGroupList){
				map.clear();
				map.put("groupId", competitionGroup.getId());
				List<CompetitionTeam> competitionTeamList = competitionTeamMapper.findCompetitionTeamList(map);
				for(int i = 0; i < competitionTeamList.size(); i++){
					CompetitionTeam competitionTeam = competitionTeamList.get(i);
					switch (competitionTeam.getNumber()) {
					case 1:
						competitionGroup.setCompetitionTeam(competitionTeam);
						break;
					case 2:
						competitionGroup.setCompetitionTeam2(competitionTeam);
						break;
					case 3:
						competitionGroup.setCompetitionTeam3(competitionTeam);
						break;
					default:
						competitionGroup.setCompetitionTeam4(competitionTeam);
						break;
					}
				}
				competitionGroup.setCompetitionTeamList(competitionTeamList);
			}
		}
		model.addAttribute("seasonId", seasonId);
		model.addAttribute("competitionGroupList", competitionGroupList);
		return "/backstage/competitionTeamList";
	}
	
	@RequestMapping("/insert")
	@ResponseBody
	public String insert(Model model, HttpServletRequest request, CompetitionTeam competitionTeam){
		String[] numberArray = request.getParameterValues("number");
		Long count = 0L;
		if(!CheckUtil.isEmpty(numberArray) && !CheckUtil.isEmpty(competitionTeam.getGroupId())){
			competitionTeamMapper.deleteByGroupId(competitionTeam.getGroupId());
			String[] teamIdArray = request.getParameterValues("teamId");
			for(int i = 0; i < numberArray.length; i++){
				Integer number = Integer.valueOf(numberArray[i]);
				Long teamId = Long.valueOf(teamIdArray[i]);
				Long userId = getCurrentUser().getId();
				competitionTeam.setNumber(number);
				competitionTeam.setTeamId(teamId);
				competitionTeam.setCreateUser(userId);
				competitionTeam.setCreateTime(new Date());
				count = competitionTeamMapper.insert(competitionTeam);
			}
		}
		return JSON.toJSONString(count>0);
	}
	
	/**
	 * 添加参赛球队页面
	 * @param model
	 * @param request
	 * @param competitionGroup
	 * @return
	 */
	@RequestMapping("/addPage")
	public String addPage(Model model, HttpServletRequest request, CompetitionGroup competitionGroup){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("seasonId", competitionGroup.getSeasonId());
		if(!CheckUtil.isEmpty(request.getParameter("teamId"))){
			Long teamId = Long.valueOf(request.getParameter("teamId"));
			map.put("teamId", teamId);
			model.addAttribute("teamId", teamId);
		}
		if(!CheckUtil.isEmpty(request.getParameter("schoolId"))){
			Long schoolId = Long.valueOf(request.getParameter("schoolId"));
			map.put("schoolId", schoolId);
			model.addAttribute("schoolId", schoolId);
		}
		List<Team> teamList = competitionTeamMapper.findNoCompetitionTeam(map);
		map.clear();
		map.put("groupId", competitionGroup.getId());
		List<CompetitionTeam> competitionTeamList = competitionTeamMapper.findCompetitionTeamList(map);
		List<School> schoolList = schoolMapper.queryBySchoolAll();
		model.addAttribute("teamList", teamList);
		model.addAttribute("competitionTeamList", competitionTeamList);
		model.addAttribute("schoolList",schoolList);
		model.addAttribute("competitionGroup", competitionGroup);
		return "/backstage/addCompetitionTeamPage";
	}
	
	/**
	 * 获取参赛球队
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/findNoCompetitionTeam")
	@ResponseBody
	public String findNoCompetitionTeam(Model model, HttpServletRequest request){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("seasonId", request.getParameter("seasonId"));
		if(!CheckUtil.isEmpty(request.getParameter("teamId"))){
			Long teamId = Long.valueOf(request.getParameter("teamId"));
			map.put("teamId", teamId);
			model.addAttribute("teamId", teamId);
		}
		if(!CheckUtil.isEmpty(request.getParameter("schoolId"))){
			Long schoolId = Long.valueOf(request.getParameter("schoolId"));
			map.put("schoolId", schoolId);
			model.addAttribute("schoolId", schoolId);
		}
		List<Team> teamList = competitionTeamMapper.findNoCompetitionTeam(map);
		return JSON.toJSONString(teamList);
	}
	
	@RequestMapping("/importTeam")
	@ResponseBody
	public void importTeam(HttpServletRequest request,HttpServletResponse response,@RequestParam(value = "file", required = false) MultipartFile file){
		List<Map<String, Object>> result = new ArrayList<Map<String,Object>>();
		Long seasonId = Long.valueOf(request.getParameter("seasonId"));
//		Boolean flag = false;
		if(file !=null && !file.isEmpty()){
			Long userId = getCurrentUser().getId();
			try {
				String fileName = file.getOriginalFilename();
				String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
				if(!fileType.equals(".xls")){
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("msg", "格式不正确，只能为.xls的格式");
					map.put("suc", false);
					result.add(map);
				}
				else{
					InputStream in=file.getInputStream();
					POIFSFileSystem poifsFileSystem = new POIFSFileSystem(in);
					HSSFWorkbook workbook = new HSSFWorkbook(poifsFileSystem);
					HSSFSheet aSheet = workbook.getSheetAt(0);
					for(int i=1; i<=aSheet.getLastRowNum();i++){
						HSSFRow aRow = aSheet.getRow(i);
						String groupName = ExcelUtil.getCellValue(aRow.getCell(0));	//第i行第1列的值
						String teamName = ExcelUtil.getCellValue(aRow.getCell(1));	//第i行第2列的值
						
						if(groupName == null || groupName.equals("")){
							Map<String, Object> map = new HashMap<String, Object>();
							map.put("msg", "第"+i+"条数据小组名称为空");
							map.put("suc", false);
							result.add(map);
							continue;
						}
						if(teamName == null || teamName.equals("")){
							Map<String, Object> map = new HashMap<String, Object>();
							map.put("msg", "第"+i+"条数据球队名称为空");
							map.put("suc", false);
							result.add(map);
							continue;
						}
						Map<String, Object> param = new HashMap<String, Object>();
						param.put("seasonId", seasonId);
						param.put("name", groupName);
						List<CompetitionGroup> competitionGroupList = competitionGroupMapper.findCompetitionGroupList(param);
						if(!CheckUtil.isEmpty(competitionGroupList)){
							Long groupId = competitionGroupList.get(0).getId();
							param.clear();
							param.put("name", teamName);
							List<Team> teamList = teamMapper.queryTeam(param);
							
							param.put("groupId", groupId);
							if(CheckUtil.isEmpty(teamList)){
								Map<String, Object> map = new HashMap<String, Object>();
								map.put("msg", "第"+i+"条数据球队名称不正确");
								map.put("suc", false);
								result.add(map);
								continue;
							}
							Long teamId = Long.valueOf(teamList.get(0).getId());
							param.clear();
							param.put("seasonId", seasonId);
							param.put("teamId", teamId);
							List<CompetitionTeam> competitionTeamList = competitionTeamMapper.findCompetitionTeamList(param);
							if(competitionTeamList.size() > 0){
								Map<String, Object> map = new HashMap<String, Object>();
								map.put("msg", "第"+i+"条数据,球队已存在");
								map.put("suc", false);
								result.add(map);
								continue;
							}
							
							param.clear();
							param.put("groupId", groupId);
							competitionTeamList = competitionTeamMapper.findCompetitionTeamList(param);
							Integer number = competitionTeamList.size();
							if(competitionTeamList.size() < 4){
								number++;
								CompetitionTeam competitionTeam = new CompetitionTeam();
								
								competitionTeam.setGroupId(groupId);
								competitionTeam.setNumber(number);
								competitionTeam.setTeamId(teamId);
								competitionTeam.setCreateUser(userId);
								competitionTeam.setCreateTime(new Date());
								competitionTeamMapper.insert(competitionTeam);
							}else{
								Map<String, Object> map = new HashMap<String, Object>();
								map.put("msg", "第"+i+"条数据小组参数球队已满");
								map.put("suc", false);
								result.add(map);
							}
						}else{
							Map<String, Object> map = new HashMap<String, Object>();
							map.put("msg", "第"+i+"条数据小组名称不正确");
							map.put("suc", false);
							result.add(map);
						}
					}
//					flag = true;
					/*Map<String, Object> map = new HashMap<String, Object>();
					map.put("msg", "导入成功!");
					map.put("suc", true);
					result.add(map);*/
				}
			} catch (Exception e) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("msg", "导入失败!");
				map.put("suc", false);
				result.add(map);
				e.printStackTrace();
			}
		}else{
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("msg", "文件为空!");
			map.put("suc", false);
			result.add(map);
		}
		
		HSSFWorkbook wb = new HSSFWorkbook();//表格
        ExcelUtil.createImportResult(wb, "importResult",result);
        String filename = "importResult"+".xls";
        response.setContentType("application/binary; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        try {
            response.setHeader("Content-Disposition", "attachment; filename=\""
                    + new String(filename.toString().getBytes("UTF-8"), "iso8859-1")
                    + "\"");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            wb.write(os);
            os.flush();
//            PrintWriter out = response.getWriter();
//            out.write("<script languge='javascript'>alert('导入成功'); window.location.href='/competitionTeam/list.htm?seasonId="+seasonId+"'</script>");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
//        return JSON.toJSONString(flag);
	}
	
	@RequestMapping("/createTeamTable")
    public void createTeamTable(HttpServletResponse response,HttpServletRequest request){
		HSSFWorkbook wb = new HSSFWorkbook();//表格
        ExcelUtil.createTeamTable(wb, "teamTable");
        String filename = "teamTable"+".xls";
        response.setContentType("application/binary; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        try {
            response.setHeader("Content-Disposition", "attachment; filename=\""
                    + new String(filename.toString().getBytes("UTF-8"), "iso8859-1")
                    + "\"");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            wb.write(os);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
